﻿@model Cxuu.Models.EditNotice
@{
    ViewData["Title"] = "发送";
}

<div class="content-top-nav">
    <div class="layui-row">
        <div class="layui-col-md11">
            <h3 style="color:#444">
                <i class="layui-icon layui-icon-home"></i>
                消息 / 写信
            </h3>
        </div>
        <div class="layui-col-md1" style="text-align:right;">
            <button class="layui-btn layui-btn-sm" onclick="loadMain('/Admin/Notice/Index')">返回列表</button>
        </div>
    </div>
    <hr>
</div>

<div class="layui-fluid" style="margin-bottom:50px;">
    <div class="layui-form">
        <form class="layui-form" action="" lay-filter="FormEdit" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="layui-form-item"> <label asp-for="GetUid" class="layui-form-label"></label> <div id="userList"></div></div>
            <div class="layui-form-item">
                <label asp-for="Title" class="layui-form-label"></label>
                <div class="layui-input-inline" style="width:280px;">
                    <input type="text" asp-for="Title" lay-verify="required" lay-reqtext="信件标题" placeholder="请输入信件标题" value="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label asp-for="Content" class="layui-form-label"></label>
                <div class="layui-input-block">
                    <textarea id="contentEdit" name="Content" class="layui-textarea" placeholder="请输入内容"></textarea>
                </div>
            </div>
            @if (await Authorizer.AuthView(PermissionKeys.Upload_Upload))
            {
                <div class="layui-form-item">
                    <label asp-for="Att" class="layui-form-label"></label>
                    <div class="layui-input-block layui-upload">
                        <div id="attval" class="cxuu_attmentupload"></div>
                        <input type="hidden" asp-for="Att" value="" class="layui-input" id="Att">
                        <button type="button" class="layui-btn" id="cxuuupload">上传</button>
                        <div style="width: 95px;">
                            <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="upload-att">
                                <div class="layui-progress-bar" lay-percent=""></div>
                            </div>
                        </div>
                        <tip>支持多个附件上传，单个附件不超过 @ViewBag.fileSize KB！ 支持格式：@ViewBag.fileExts </tip>
                    </div>
                </div>
            }
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="saveBtn" id="saveBtn"><i class="layui-icon">&#xe605;</i>@ViewData["Title"]</button>
                </div>
            </div>
        </form>
    </div>
</div>
<script type="text/javascript" src="~/lib/tinymce/tinymce.min.js?v=5.10"></script>
<script>

    layui.define(function () {
        var form = layui.form, layer = layui.layer, $ = layui.jquery,
            upload = layui.upload, element = layui.element, transfer = layui.transfer;

        form.render();

        tinymce.init({
            selector: '#contentEdit',
            language: 'zh_CN',
            relative_urls: false,
            remove_script_host: true,
            plugins: 'print preview searchreplace autolink directionality visualblocks visualchars image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autoresize  axupimgs',
            toolbar: 'code | undo redo restoredraft | cut copy paste | forecolor bold italic underline link | alignleft aligncenter alignright alignjustify outdent indent | fontselect fontsizeselect | table  charmap emoticons insertdatetime preview | image axupimgs',
            autosave_interval: "20s",//自动存稿时间
            font_formats: '微软雅黑=Microsoft YaHei,sans-serif;仿宋_GB2312=仿宋_GB2312,Microsoft YaHei,sans-serif;宋体=宋体;仿宋=仿宋;黑体=黑体',
            height: 650, //编辑器高度
            min_height: 400,
            draggable_modal: true,
            images_upload_base_path: '/',
            images_reuse_filename: true,
            images_upload_handler: function (blobInfo, succFun, failFun) {
                var xhr, formData;
                var file = blobInfo.blob();//转化为易于理解的file对象
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', '/Admin/Upload/Upload?type=Tinymce&source=Notice');
                xhr.onload = function () {
                    var json;
                    if (xhr.status != 200) {
                        failFun('HTTP Error: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);
                    if (!json || typeof json.location != 'string') {
                        failFun('Invalid JSON: ' + xhr.responseText);
                        return;
                    }
                    succFun(json.location);
                };
                formData = new FormData();
                formData.append('file', file, file.name);
                //console.log(xhr);
                xhr.send(formData);
            }
        });

        $.getJSON("/Admin/Notice/AddOrEdit?jsonUser=1", function (res) {
            // console.log(res);
            transfer.render({
                elem: '#userList'
                , data: res.data
                , title: ['用户列表', '收件用户']
                , showSearch: true
                , id: 'transferList'
                , parseData: function (resData) {
                    return {
                        "value": resData.id
                        , "title": resData.deptName + " - " + resData.nickname
                        , "disabled": resData.disabled  //是否禁用
                        , "checked": resData.checked //是否选中
                    }
                }
            });
        });

        var uploadInst = upload.render({
            elem: '#cxuuupload'
            , url: '/Admin/Upload/Upload?type=layui&source=Notice'
            , size: "@ViewBag.fileSize"
            , accept: 'file'
            , acceptMime: 'file/*'
            //, exts: 'zip|rar|7z|doc|docx|xlsx|xls|'
            , exts: "@ViewBag.fileExts".replace(/./g, '')
            , before: function (obj) {
                element.progress('upload-att', '0%'); //进度条复位
                layer.msg('上传中', { icon: 16, time: 0 });
            }
            , done: function (res) {
                if (res.status == 1) {
                    $('#attval').append('<span id="attidd' + res.pkey + '" class="layui-badge layui-bg-blue"> ID：' + res.pkey + ' 文件名：' + res.data.filename + ' <a href="javascript:;" onclick="attColse(' + res.pkey + ')" ><i class="layui-icon layui-icon-close"></i></a></span>');
                    var input = $("#Att").val();
                    if (input != "" && input != undefined) {
                        $("#Att").val($("#Att").val() + "," + res.pkey);
                    } else {
                        $('#Att').val(res.pkey);
                    }
                    layer.msg(res.info);
                } else {
                    layer.msg("上传失败！");
                }
            }
            //进度条
            , progress: function (n, elem, e) {
                element.progress('upload-att', n + '%');
                if (n == 100) {
                    layer.msg('上传完毕', { icon: 1 });
                }
            }
        });

        var dataPost = function (url, data) {
            $.post(url, data, function (res) {
                if (res.status == 1) {
                    $("#saveBtn").hide();
                    layer.msg(res.msg, { icon: 1, time: 1000 }, function () {
                        loadMain('/Admin/Notice/Index/');
                    });
                } else {
                    layer.msg(res.msg, { icon: 2, anim: 6, time: 5000 });
                }
            });
        };

        //监听提交
        $('#saveBtn').click(function () {
            let getUserId = getParamValues('value', transfer.getData('transferList')).toString();
            //console.log(getUserId);
            var field = form.val('FormEdit');
            var post = {
                GetUid: getUserId,
                Title: field.Title,
                Content: tinyMCE.activeEditor.getContent(),
                Att: field.Att,
            };
            dataPost('/Admin/Notice/CreatePost', post);
            return false;
        });

    });
    //提取UID
    function getParamValues(value, arr) {
        var ret = []
        for (var i = 0, len = arr.length; i < len; i++) {
            ret.push(arr[i][value])
        }
        return ret
    }


    function attColse(id) {
        layer.confirm('真的删除这个附件吗？', { icon: 3, title: '警告' }, function (index) {
            $.post('/Admin/Attment/Delete', { id: id }, function (res) {
                if (res.status == 1) {
                    layer.msg("附件: " + res.msg);
                    $('#attidd' + id).remove();
                    var input = $("#Att").val();
                    var newarr = input.split(",");
                    newarr.splice($.inArray("" + id + "", newarr), 1);
                    $('#Att').val(newarr);
                } else {
                    layer.msg("附件: " + res.msg + "请查看是否有删除附件权限");
                }
            });
            layer.close(index);
        });
    }
</script>